//
//  GetData.m
//  OpperV1.0
//
//  Created by Le Dung on 5/10/13.
//  Copyright (c) 2013 LeDung. All rights reserved.
//

#import "GetData.h"

@implementation GetData

+(BOOL)addMember:(Member *)member
{
    return YES;
}

+(void)getListProfile
{
    NSString *functionName =@"getListProfile";
    NSMutableDictionary *dictionary =[[[NSMutableDictionary alloc]init] autorelease];
    [dictionary setValue:[GetData App].userAccount.userId forKey:@"member_id"];
    [dictionary setValue:[GetData App].userAccount.userName forKey:@"username"];
    [dictionary  setValue:[GetData App].userAccount.password forKey:@"passwd"];
    NSString *jsonRespones =[GetData sendRequest:functionName andDictionary:dictionary];
    
    for(Profile *unit in   [GetData getMember:[GetData fetchJson:jsonRespones andKey:@"members"]])
    {
        [[GetData App].profileArray addObject:unit];
    }
}



+(NSMutableArray *)getMember:(NSArray*)array
{
    NSMutableArray *memberArray =[[NSMutableArray alloc]init];
    for(NSDictionary *unit in array)
    {
        Member *member =[[Member alloc]init];
        member.idMember=[unit objectForKey:@"id"];
        member.firstName=[unit objectForKey:@"first_name"];
        member.lastname=[unit objectForKey:@"last_name"];
        member.faceId=[unit objectForKey:@"facebookid"];
        member.gender=[unit objectForKey:@"gender"];
        member.address=[unit objectForKey:@"address"];
        member.houseNumber=[unit objectForKey:@"house_number"];
        member.postCode=[unit objectForKey:@"postcode"];
        member.place=[unit objectForKey:@"place"];
        member.phoneNumber=[unit objectForKey:@"phone"];
        member.birthDay=[unit objectForKey:@"birthday"];
        member.owner=[unit objectForKey:@"owner"];
        member.death=[unit objectForKey:@"death"];
        member.starDate=[unit objectForKey:@"start_date"];
        member.endDate=[unit objectForKey:@"end_date"];
        [memberArray addObject:member];
    }
    return [memberArray autorelease];
}



+(BOOL)checkError:(NSString*)jsonString
{

    NSString *error= [NSString stringWithFormat:@"%@", (NSString*)[GetData fetchJson:jsonString andKey:@"error"]];
    NSLog(@"error : %@",error);
    if([error isEqualToString:@"0"])
    {
        return NO;
    }
    return YES;
    
}

+(NSString *)checkMassage:(NSString*)jsonString
{
    NSString* massage= (NSString*)[GetData fetchJson:jsonString andKey:@"msg"];
    return massage;
    
}


+(void )login:(NSString*)jsonString
{
    NSDictionary *array =[GetData fetchJson:jsonString];
    NSDictionary *dictionary =[array objectForKey:@"userId"];
    [GetData App].userAccount.email=[dictionary objectForKey:@"email"];
    [GetData App].userAccount.userId=[dictionary objectForKey:@"id"];
    [GetData App].userAccount.registerId=[dictionary objectForKey:@"register_id"];
    [GetData App].userAccount.userName=[dictionary objectForKey:@"username"];

}


+(AppDelegate *)App
{
    AppDelegate *appdelegate =[[UIApplication sharedApplication]delegate];
    
    return appdelegate;
}


+(NSMutableArray *)getContractList:(NSString*)memberId
{
    NSMutableArray *contractArray =[[NSMutableArray alloc]init];
    
    NSMutableDictionary *dictionary =[[[NSMutableDictionary alloc]init] autorelease];
    NSString *functionName=@"getListContract";
    [dictionary setValue:[GetData App].userAccount.userId forKey:@"member_id"];
    [dictionary setValue:[GetData App].userAccount.userName forKey:@"username"];
    [dictionary  setValue:[GetData App].userAccount.password forKey:@"passwd"];

    NSString *jsonRespones =[GetData sendRequest:functionName andDictionary:dictionary];
    
    NSLog(@"contractlist : %@",jsonRespones);
        for(ContractInfo *unit in   [GetData getContractUnit:[GetData fetchJson:jsonRespones andKey:@"contracts"]])
    {

        [contractArray addObject:unit];
    }
    return [contractArray autorelease];
}

+(NSMutableArray*)getContractUnit:(NSArray*)array
{
    
    NSMutableArray *mArray =[[NSMutableArray alloc]init];
    for(NSDictionary *unit in array)
    {
        ContractInfo *contract =[[ContractInfo alloc]init];
        contract.contractId=[unit objectForKey:@"id"];
        contract.contractNumber=[unit objectForKey:@"contract_number"];
        contract.contractName=[unit objectForKey:@"contract_name"];
        contract.memberId=[unit objectForKey:@"member_id"];
        contract.categoryId=[unit objectForKey:@"category_id"];
        contract.productId=[unit objectForKey:@"product_id"];
        contract.providerId=[unit objectForKey:@"provider_id"];
        contract.contractStartDate=[unit objectForKey:@"start_date"];
        contract.contractEndDate=[unit objectForKey:@"end_date"];
        contract.terminalAlert=[unit objectForKey:@"termination_alert"];
        contract.terminalDate=[unit objectForKey:@"termination_date"];
        contract.productName=[unit objectForKey:@"product_name"];
        contract.providerName=[unit objectForKey:@"provider_name"];
        [mArray addObject:contract];
        [contract release];

    }
    return [mArray autorelease];

    
}

+(NSMutableArray *)productFilter :(NSMutableArray *)destinationArray andCategoryId:(NSString*)categoryId andProviderId :(NSString *)providerId
{
    
    
    [destinationArray removeAllObjects];
    for(ProductClass *unitProduct in [GetData App].productArray)
    {
        
        if([unitProduct.productCategoryId isEqualToString:categoryId] && [unitProduct.productProviderId isEqualToString:providerId])
        {
            ListObject *listObject =[[ListObject alloc]init   ];
            listObject.objectName=unitProduct.productName;
            listObject.objectId=unitProduct.idAutoIncr ;
            [destinationArray addObject:listObject];
            [listObject release];
        }
    }
    
    
    return destinationArray;
}



+(void)getListData
{
        NSString *functionName=@"getCategorys";
        NSString *jsonString=[GetData sendRequest:functionName andDictionary:nil];
    
    [GetData checkError:jsonString];
        if(jsonString)
        {
            for(CategoryClass *unit in   [GetData getCategorys:[GetData fetchJson:jsonString andKey:@"categorys"]])
            {
               
                [[GetData App].catagoryArray addObject:unit];
            }
            //get providers
            for(ProviderClass *unit in   [GetData getProvider:[GetData fetchJson:jsonString andKey:@"providers"]])
            {
                [[GetData App].providerArray addObject:unit];
            }
            //product
            for(ProductClass *unit in   [GetData getProduct:[GetData fetchJson:jsonString andKey:@"products"]])
            {
                [[GetData App].productArray addObject:unit];
            }
            
        }
}



+(NSMutableArray *)getCategorys:(NSArray*)array
{
    NSMutableArray *categoryArray =[[NSMutableArray alloc]init];
    for(NSDictionary *unit in array)
    {
        CategoryClass *unitCategory =[[CategoryClass alloc]init];
        unitCategory.idAutoIncr=[unit objectForKey:@"id"];
        unitCategory.categoryName=[unit objectForKey:@"category_name"];
        unitCategory.registerDate=[unit objectForKey:@"register_date"];
        unitCategory.registerId=[unit objectForKey:@"register_id"];
        [categoryArray addObject:unitCategory ];
        [unitCategory release];
    }
    return [categoryArray autorelease];
}

+(NSMutableArray *)getProvider:(NSArray*)array
{
    NSMutableArray *providerArray =[[NSMutableArray alloc]init];
    for(NSDictionary *unit in array)
    {
        ProviderClass *unitProvider =[[ProviderClass alloc]init];
        unitProvider.idAutoIncr=[unit objectForKey:@"id"];
        unitProvider.providerName=[unit objectForKey:@"provider_name"];
        [providerArray addObject:unitProvider];
        [unitProvider release];
    }
    return [providerArray autorelease];
}



+(NSMutableArray *)getProduct:(NSArray*)array
{
    NSMutableArray *productArray =[[NSMutableArray alloc]init];
    for(NSDictionary *unit in array)
    {
        ProductClass *unitCategory =[[ProductClass alloc]init];
        unitCategory.idAutoIncr=[unit objectForKey:@"id"];
        unitCategory.productName=[unit objectForKey:@"product_name"];
        unitCategory.productCategoryId=[unit objectForKey:@"category_id"];
        unitCategory.productProviderId=[unit objectForKey:@"provider_id"];
        [productArray addObject:unitCategory ];
        [unitCategory release];
    }
    return [productArray autorelease];
    
}





+(NSString*) sendRequest:(NSString *)functionName andDictionary:(NSMutableDictionary *)dictionary
{
    
    NSString *jsonStringRequest=nil;
    NSString * errorMessage;

    if(dictionary)
    {
    NSData *jsonData =[NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:nil ];
    jsonStringRequest =[[[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding] autorelease];
    }
    
    NSString *body =[NSString stringWithFormat:@"method=%@&request=%@",functionName,jsonStringRequest];
    
    NSLog(@"body -------%@",body);
    NSString *urlString=@"http://host90.r-iv.nl/webservice/webserver/";
    NSURL *url =[NSURL URLWithString:urlString];
    NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:url];

    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
    [request setTimeoutInterval:10];
    NSURLResponse   *responsel;
    NSError *error= nil;
    
    NSData *data =[NSURLConnection sendSynchronousRequest:request returningResponse:&responsel error:&error];
    
    if(!error && data)
    {
        NSString *resString =[[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding] autorelease];
        
        NSScanner* scanner = [NSScanner scannerWithString:resString];
        NSString* targetString; 
        [scanner scanUpToString:@"<status>" intoString:&targetString];
        [scanner scanUpToString:@"</status>" intoString:&targetString];
        
        targetString= [targetString stringByReplacingOccurrencesOfString:@"<status>" withString:@""];
        if([targetString isEqualToString:@"success"])
        {
            
            NSString *resString =[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            NSScanner* scanner = [NSScanner scannerWithString:resString];
            [resString release];
            NSString* targetJson; 
            [scanner scanUpToString:@"<response>" intoString:&targetJson];
            [scanner scanUpToString:@"</response>" intoString:&targetJson];
            targetJson= [targetJson stringByReplacingOccurrencesOfString:@"<response>" withString:@"" ];
            
            return targetJson;
 
        }
        else
        {
            errorMessage =@"Sever was wrong";
        }

    }
    else
    {
        errorMessage=@"Connect false, Please check connection.";
    }
    
    UIAlertView *alertView =[[UIAlertView alloc]initWithTitle:errorMessage message:nil delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles: nil];
    [alertView show];
    [alertView release];
    return  nil;
    
    
    
}


+(NSArray *)fetchJson:(NSString *)resString andKey:(NSString *)keyWord
{
    NSData *resData = [resString dataUsingEncoding:NSUTF8StringEncoding];
    NSError* error;
    NSDictionary* json = [NSJSONSerialization
                          JSONObjectWithData:resData
                          
                          options:kNilOptions
                          error:&error];
    
    NSArray* resArray = [json objectForKey:keyWord]; //2
    
        return resArray;
}

+(NSDictionary *)fetchJson:(NSString *)resString
{
    NSData *resData = [resString dataUsingEncoding:NSUTF8StringEncoding];
    NSError* error;
    NSDictionary* jsonDictionary = [NSJSONSerialization
                          JSONObjectWithData:resData
                          
                          options:kNilOptions
                          error:&error];    
    return jsonDictionary;
}


+(NSUserDefaults *)UserDefault
{
    NSUserDefaults *userDefault =[NSUserDefaults standardUserDefaults];
    return  userDefault ;
}



+(NSData * )dictionaryToData :(NSMutableDictionary*)dictionary
{
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:dictionary];
    return data;
}

+(NSMutableDictionary *)dataToDictionary:(NSData*)data
{
    NSMutableDictionary *dictionary = (NSMutableDictionary  *) [NSKeyedUnarchiver unarchiveObjectWithData:data];
    return  dictionary;
}






@end
